﻿
namespace KingerRobot.MexicoSailunMDC.Biz;
/// <summary>
/// 入库扫描仪任务创建(新版逻辑)
/// 入库扫描(新版配对)
/// </summary>
public class LineScannerCreateTaskBiz : K8.MDCBB.Biz

{
    private const string ClassName = nameof(LineScannerCreateTaskBiz);


    #region 配置参数
    //ProductCodeA 远离扫码头位置
    //ProductCodeB 靠近扫码头位置
    private ParamData Param { get; set; }

    class ParamData
    {


        /// <summary>
        /// 扫描仪位置ID
        /// </summary>
        public long LineScannerLoc { get; set; }

    }
    #endregion

    #region PLC 通讯参数
    private ValueData Data { get; set; }
    class ValueData
    {
        /// <summary>
        /// 产品条码
        /// </summary>
        public string ProductCode { get; set; }
        /// <summary>
        /// 计数
        /// </summary>
        public long TireCount { get; set; }
        /// <summary>
        /// 读取任务号（上段线体任务读取后【有值】）才下传新任务
        /// </summary>
        public int RWorkNo { get; set; }

        public int RStatus { get; set; }

        public string ProductCodeA1 { get; set; }
        public string ProductCodeA2 { get; set; }
        public string ProductCodeA3 { get; set; }
        public string ProductCodeA4 { get; set; }
        public string ProductCodeA5 { get; set; }
        public string ProductCodeA6 { get; set; }
        public string ProductCodeA7 { get; set; }
        public string ProductCodeA8 { get; set; }
        public string ProductCodeA9 { get; set; }
        public string ProductCodeA10 { get; set; }
        public string ProductCodeA11 { get; set; }
        public string ProductCodeA12 { get; set; }


        public string ProductCodeB1 { get; set; }
        public string ProductCodeB2 { get; set; }
        public string ProductCodeB3 { get; set; }
        public string ProductCodeB4 { get; set; }
        public string ProductCodeB5 { get; set; }
        public string ProductCodeB6 { get; set; }
        public string ProductCodeB7 { get; set; }
        public string ProductCodeB8 { get; set; }
        public string ProductCodeB9 { get; set; }
        public string ProductCodeB10 { get; set; }
        public string ProductCodeB11 { get; set; }
        public string ProductCodeB12 { get; set; }

    }
    #endregion

    #region 缓存
    private CacheData Cache { get; set; }
    class CacheData
    {
        /// <summary>
        /// 计数
        /// </summary>
        public long TireCount { get; set; }

        public string ScannerProduct { get; set; }

        public string ProductCode { get; set; }


    }
    #endregion

    #region 实时日志
    private StepData Step { get; set; }
    class StepData
    {
        private string _msg = string.Empty;
        public string StepMsg
        {
            get
            {
                return this._msg;
            }
            set
            {
                if (string.IsNullOrWhiteSpace(value))
                {
                    this._msg = string.Empty;
                    return;
                }
                this._msg = $"{ClassName}|{System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}>>{value}";
            }
        }
        public Status RStatus { get; set; }
    }
    private void StepMsg(string msg)
    {
        this.Step.StepMsg = msg;
        WriteLog(msg);
    }
    #endregion

    #region 文件日志（运行需要 Nlog 配置）
    private void WriteLog(string message)
    {
        K8.LSF.Client.Log(new K8.LSF.Log { Data = message });
    }
    #endregion 

    /// <summary>
    /// 和 PLC 通讯对象
    /// </summary>
    private BizData BizData { get; set; }

    class Status
    {
        public Status(int status)
        {
            this.HeightType = status >> 4 & 1;
        }
        public int HeightType { get; set; }
    }
    public int Execute(BizData writer)
    {
        // Excute 方法外使用 BizData
        this.BizData = writer;
        //int heightType = Value.RStatus;
        // 返回参数
        var result = 0;

        this.StepMsg($"扫码头{Param.LineScannerLoc}开始执行");

        if (Data.ProductCodeA1 == "\u0000" || Data.ProductCodeA2 == "\u0000"
            || Data.ProductCodeA3 == "\u0000" || Data.ProductCodeA4 == "\u0000"
            || Data.ProductCodeA5 == "\u0000" || Data.ProductCodeA6 == "\u0000"
            || Data.ProductCodeA7 == "\u0000" || Data.ProductCodeA8 == "\u0000"
            || Data.ProductCodeA9 == "\u0000" || Data.ProductCodeA10 == "\u0000"
            || Data.ProductCodeA11 == "\u0000" || Data.ProductCodeA12 == "\u0000")
        {
            this.StepMsg($"条码信息不全3");
            return result;
        }



        StringBuilder sbA = new StringBuilder();
        sbA.Append(Data.ProductCodeA1);
        sbA.Append(Data.ProductCodeA2);
        sbA.Append(Data.ProductCodeA3);
        sbA.Append(Data.ProductCodeA4);
        sbA.Append(Data.ProductCodeA5);
        sbA.Append(Data.ProductCodeA6);
        sbA.Append(Data.ProductCodeA7);
        sbA.Append(Data.ProductCodeA8);
        sbA.Append(Data.ProductCodeA9);
        sbA.Append(Data.ProductCodeA10);
        sbA.Append(Data.ProductCodeA11);
        sbA.Append(Data.ProductCodeA12);
        // 获取条码
        var productCodeA = sbA.ToString();  //Data.ProductCode;
        // 条码为空
        if (string.IsNullOrWhiteSpace(productCodeA) || productCodeA.StartsWith(ConstFields.Default))
        {
            this.StepMsg($"{productCodeA}条码为空, 扫描仪{Param.LineScannerLoc}-线体任务:{Data.RWorkNo}");
            return result;
        }
        // 条码为空
        if (string.IsNullOrWhiteSpace(productCodeA) || productCodeA.Length < 12)
        {
            this.StepMsg($"{productCodeA}条码信息不全2");
            return result;
        }

        this.StepMsg($"条码A1读到 {productCodeA}");
        BizTaskBean task = new();
        var startLoc = Param.LineScannerLoc;
        IWarehousingBeforeService warehousingBeforeService = K8.RSF.Client.Create<IWarehousingBeforeService>();
        //创建扫码记录
        if (Cache.ScannerProduct != productCodeA)
        {
            var scannerResult = warehousingBeforeService.CreatePairScanner(startLoc, productCodeA);
            if (scannerResult > 0)
            {
                Cache.ScannerProduct = productCodeA;
            }
        }


        // 获取条码
        var productCodeB = "";

        if (Data.ProductCodeB1 == "\u0000" || Data.ProductCodeB2 == "\u0000"
    || Data.ProductCodeB3 == "\u0000" || Data.ProductCodeB4 == "\u0000"
    || Data.ProductCodeB5 == "\u0000" || Data.ProductCodeB6 == "\u0000"
    || Data.ProductCodeB7 == "\u0000" || Data.ProductCodeB8 == "\u0000"
    || Data.ProductCodeB9 == "\u0000" || Data.ProductCodeB10 == "\u0000"
    || Data.ProductCodeB11 == "\u0000" || Data.ProductCodeB12 == "\u0000")
        {
            this.StepMsg($"条码信息不全4");
            //判断超时 (超时在wcs中判断)
            productCodeB = ConstFields.Default;

        }
        else
        {

            StringBuilder sbB = new StringBuilder();
            sbB.Append(Data.ProductCodeB1);
            sbB.Append(Data.ProductCodeB2);
            sbB.Append(Data.ProductCodeB3);
            sbB.Append(Data.ProductCodeB4);
            sbB.Append(Data.ProductCodeB5);
            sbB.Append(Data.ProductCodeB6);
            sbB.Append(Data.ProductCodeB7);
            sbB.Append(Data.ProductCodeB8);
            sbB.Append(Data.ProductCodeB9);
            sbB.Append(Data.ProductCodeB10);
            sbB.Append(Data.ProductCodeB11);
            sbB.Append(Data.ProductCodeB12);
            productCodeB = sbB.ToString();

        }

        //return result;


        //// 创建扫码记录
        //if (Cache.ScannerProduct == productCodeA)
        //{
        //    this.StepMsg($"{productCodeA}通过日志记录跟踪，条码 {productCodeA}已创建扫描记录");
        //    return result;
        //}
        if (Cache.ProductCode == productCodeA)
        {
            this.StepMsg($"条码 {productCodeA}已创建任务");
            return result;
        }
        this.StepMsg($"条码A2读到 {productCodeA},条码B2读到 {productCodeB}");
        //return result;

        //BizTaskBean task = new();
        //IWarehousingBeforeService warehousingBeforeService = K8.RSF.Client.Create<IWarehousingBeforeService>();


        var taskId = warehousingBeforeService.CreatePairTask(startLoc, productCodeA, productCodeB);
        this.StepMsg($"扫码头{Param.LineScannerLoc}-条码{productCodeA},创建任务返回值{taskId}");
        if (taskId > 0)
        {
            ITaskService taskService = K8.RSF.Client.Create<ITaskService>();
            task = taskService.GetTaskBeanByProductCode(productCodeA);
            if (task is null)
            {
                this.StepMsg($"不存在未执行的入库任务");
                return result;
            }
            var mark = SetTaskInfo(task);
            if (mark > 0)
            {
                // 执行、保存缓存
                //修改任务下发状态
                taskService.UpdateTaskDown(task.TaskNo, 1);
                this.StepMsg($"条码：{productCodeA},任务{task.TaskNo}-修改状态");

                var service = K8.RSF.Client.Create<IWarehousingBeforeService>();
                service.ExecuteTask(task.TaskNo ?? 0, startLoc);

                this.StepMsg($"条码：{productCodeA},任务{task.TaskNo}-执行完成");
                Cache.ProductCode = productCodeA;
            }
        }

        return result;

    }
    private int SetTaskInfo(BizTaskBean task)
    {
        var result = 0;
        var sProductCode = task.ProductCode;

        //如果是出库任务 则为直运类型 目的地plccode取指令的plccode
        string destination = task.TargetPlcLoc;
        if (task.TaskType == (int)EnumTaskType.Exwarehouse)
        {
            destination = task.TargetCmdPlcLoc;
        }

        var taskNo = task.TaskNo;
        //var outSize = task?.OutSize ?? 0;
        var groupNo = task.TaskGroup;
        this.StepMsg($"获取任务完成,task{task.ToJson()}");
        //if (string.IsNullOrWhiteSpace(destination) || string.IsNullOrWhiteSpace(sProductCode) || destination == "0" || taskNo == 0)
        //{
        //    this.StepMsg($"下传失败,参数异常{task.ToJson()}");
        //    return 0;
        //}


        try
        {
            this.StepMsg($"任务{taskNo}开始下传11111");

            if (destination.Contains("9999") || destination.Contains("8888"))
            {
                result = this.BizData.WriteData(new
                {
                    Destination = destination,        // 目标地址： 如果是异常胎下达目的地是9999,正常胎下达目的地是8888
                    WorkNo = taskNo,                   // 流水号
                    GroupId = destination,                 // 组号
                });
            }
            else
            {
                result = this.BizData.WriteData(new
                {
                    Destination = destination,        // 目标地址
                    WorkNo = taskNo,                   // 流水号
                    GroupId = groupNo,                 // 组号
                });
            }

              
            this.StepMsg($"任务{taskNo}下传完成,,{result}");

        }
        catch (Exception ex)
        {
            this.StepMsg($"任务{taskNo}下传失败1,参数异常{task.ToJson()}");
            return 0;

        }
        return 1;
    }
}
